//
//  ZZZThemeSetVc.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/10/2.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZZThemeSetVc.h"
#import "ZZLightViewSettingCVCellModel.h"
#import "ZZLightViewSettingCollectionViewCell.h"
#import "ZZColorRGBA.h"
#import "ZZThemeCellModel.h"
#import "UIImage+ZUtilities.h"

#define kCollectionViewCellIdentifer @"collectionViewCellIdentifer"
@interface ZZZThemeSetVc ()<UICollectionViewDelegate,UICollectionViewDataSource>
// 名字
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;


@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIImageView *lightImage;
// 中间圆View
@property (weak, nonatomic) IBOutlet ZZView *circleCenterView;


//
@property (nonatomic, strong)ZZThemeCellModel *changeModel;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *collectionViewFlow;
@property (nonatomic, strong)NSMutableArray<ZZLightViewSettingCVCellModel *> *cellModels;
@property (nonatomic, strong) ZZLightViewSettingCVCellModel*currentSelectModel;
// 选择的那个模型

// 灯的图标
@property (weak, nonatomic) IBOutlet UIImageView *lightView;
// 圆盘内的View
@property (weak, nonatomic) IBOutlet UIButton *moveColorView;

@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;

// 频率
@property (weak, nonatomic) IBOutlet UISlider *pingLvSlider;
// 亮度
@property (weak, nonatomic) IBOutlet UISlider *lightSlider;


@end

@implementation ZZZThemeSetVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *label = [UILabel new];
    label.font = [UIFont systemFontOfSize:17];
    label.text = NSLocalizedString(@"THEME_Setting_Title", nil);
    label.textColor = [UIColor whiteColor];
    label.frame = CGRectMake(0, 0, 100, 44);
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"icon_fanh"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 32, 32);
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];

    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0, 32, 32);
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [saveBtn setTitle:NSLocalizedString(@"THEME_Setting_Save",nil) forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor zColorWithRed:248 green:204 blue:40] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    self.view.backgroundColor = [UIColor blackColor];

    
    
    
    [self setupSubView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(btn2Move:)];
    [self.moveColorView addGestureRecognizer:pan];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.scrollView setContentSize:CGSizeMake(Z_SCREEN_WIDTH, 1200)];
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - setupSubView
- (void)setupSubView {
    
    self.moveColorView.backgroundColor = [UIColor clearColor];
    self.moveColorView.layer.cornerRadius = 12.5;
    self.moveColorView.layer.borderWidth = 2;
    self.moveColorView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZZLightViewSettingCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kCollectionViewCellIdentifer];
    self.collectionViewFlow.itemSize = CGSizeMake(60, 45);
    self.collectionViewFlow.minimumInteritemSpacing = 4;
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    self.deleteBtn.layer.borderColor = [UIColor grayColor].CGColor;
    self.deleteBtn.layer.cornerRadius = 12.5;
    self.deleteBtn.layer.borderWidth = 1;
    self.deleteBtn.layer.masksToBounds = YES;
    
    [self setSliderView:self.lightSlider];
    [self setSliderView:self.pingLvSlider];
    
    [self.lightSlider addTarget:self action:@selector(sliderViewValueChange) forControlEvents:UIControlEventValueChanged];
     [self.pingLvSlider addTarget:self action:@selector(pingLvSliderViewValueChange) forControlEvents:UIControlEventValueChanged];
    
    self.circleCenterView.viewDidClick = ^(UIColor *color, CGPoint location) {
        
        if (self.currentSelectModel == nil) {
            return ;
        }
        self.moveColorView.center = location;
        self.currentSelectModel.color = color;
           self.lightImage.image = [self.lightImage.image imageWithColors:[ZZColorRGBA colorsFromRGBA:self.changeModel.colors]];
        [self.collectionView reloadData];
        self.lightImage.image = [UIImage imageNamed:self.changeModel.imageStr];
        self.lightView.image = [self.lightView.image imageWithColors:[ZZColorRGBA colorsFromRGBA:self.changeModel.colors]];
    };
}


- (void)setSliderView:(UISlider *)slider {
    
    slider.backgroundColor = [UIColor zColorWithHex:0x34373b];
    slider.minimumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.maximumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.layer.cornerRadius = 8;
    [slider setThumbImage:[UIImage imageNamed:@"icon_huaik"] forState:UIControlStateNormal];
}
#pragma mark - action

- (IBAction)deleteColor:(id)sender {
    
    if (self.cellModels.count >1 && self.currentSelectModel.isSelect == YES) {
        
        [self.changeModel.colors removeObjectAtIndex:[self.cellModels indexOfObject:self.currentSelectModel]];
        [self.cellModels removeObject:self.currentSelectModel];
        
        self.currentSelectModel = nil;
        [self.collectionView reloadData];
        self.lightImage.image = [UIImage imageNamed:self.changeModel.imageStr];
        self.lightView.image = [self.lightView.image imageWithColors:[ZZColorRGBA colorsFromRGBA:self.changeModel.colors]];
#pragma 可以输出颜色
        // 遍历模型cellModels每个模型有相应的颜色
    }
}


// 亮度值改变
- (void)sliderViewValueChange {
    
    NSLog(@"%lf",self.lightSlider.value);
    self.changeModel.lightValue = self.lightSlider.value;
}

// 频率值改变
- (void)pingLvSliderViewValueChange{
    
    NSLog(@"%lf",self.pingLvSlider.value);
    self.changeModel.pinLv = self.pingLvSlider.value;
}
// 改变名字
- (IBAction)changeBtn:(UIButton *)sender {
    
    UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"修改名称"
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];
    
    __block UITextField *nameTextFIeld = nil;
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        nameTextFIeld = textField;
    }];
    
    
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {}];
    
    UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           
                                                           if (nameTextFIeld.text.length == 0) {
                                                               
                                                               
                                                               return ;
                                                           }
                                                           self.nameLabel.text = nameTextFIeld.text;
                                                           self.changeModel.title = nameTextFIeld.text;
                                                       }];
    [alertVc addAction:defaultAction];
    [alertVc addAction:sureAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (IBAction)changModel:(UIButton *)sender {
    
    NSInteger tag = sender.tag - 2001;
    self.changeModel.modelStyle = tag;
    switch (tag) {
        case 0:
        {
            self.lightView.image = [UIImage imageNamed:@"img_theme01"];
            
        }
            break;
        case 1:
        {
            // 点击1
             self.lightView.image = [UIImage imageNamed:@"img_theme02"];
        }
            break;
        case 2:
        {
            // 点击1
             self.lightView.image = [UIImage imageNamed:@"img_theme03"];
        }
            break;
        case 3:
        {
             self.lightView.image = [UIImage imageNamed:@"img_theme04"];
        }
            break;
        case 4:
        {
             self.lightView.image = [UIImage imageNamed:@"img_theme05"];
        }
            break;
            
        default:
            break;
    }
    
    NSArray *arr = [ZZColorRGBA colorsFromRGBA:self.changeModel.colors];
    self.lightView.image = [self.lightView.image imageWithColors:arr];
}



#pragma mark - Func
- (void)back {
    
    if ([self.model isEqualToModel:self.changeModel]) {
        
         [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"尚未保存修改，你需要保存？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [self.navigationController popViewControllerAnimated:YES];
                                                              }];
        
        [alert addAction:defaultAction];
        
        UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               
                                                               [self.model equalToModel:self.changeModel];
                                                               // 保存并推出
                                                               if(self.updateData) {
                                                                   
                                                                   self.updateData(self.model);
                                                               }
                                                               
                                                               [self.navigationController popViewControllerAnimated:YES];
                                                           }];
        
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
   
}

- (void)saveBtnClick {
    
    [self.model equalToModel:self.changeModel];
    if (self.updateData) {
        
        self.updateData(self.model);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - collectionView D & D
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.cellModels.count +1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    ZZLightViewSettingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellIdentifer forIndexPath:indexPath];
    
    if (self.cellModels.count == indexPath.row) {
        
        ZZLightViewSettingCVCellModel *model = [ZZLightViewSettingCVCellModel new];
        
        model.isSelect = NO;
        model.model =  ZZLightViewSettingCVCellStyleAdd;
        cell.model = model;
    } else {
        
         cell.model = self.cellModels[indexPath.row];
    }
    
   
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.cellModels.count == indexPath.row) {

        if (self.cellModels.count >= 4) {

            [MBProgressHUD zAlertError:@"最多4种颜色"];
            return;
        }

        self.currentSelectModel.isSelect = NO;
        self.currentSelectModel = nil;
        
        ZZLightViewSettingCVCellModel*model2 = [ZZLightViewSettingCVCellModel new];
        model2.model = ZZLightViewSettingCVCellStyleSelect;
        model2.color = [UIColor redColor];
        [self.cellModels addObject:model2];
        [self.collectionView reloadData];
        [self.changeModel.colors addObject: [ZZColorRGBA colorRGBAWithR:255.0 G:0 B:0 A:1]];

        self.lightImage.image = [UIImage imageNamed:self.changeModel.imageStr];
        self.lightView.image = [self.lightView.image imageWithColors:[ZZColorRGBA colorsFromRGBA:self.changeModel.colors]];

        
        
    } else {
        
        self.currentSelectModel.isSelect = NO;
        ZZLightViewSettingCVCellModel *model = self.cellModels[indexPath.row];
        model.isSelect = YES;
        
        self.currentSelectModel = model;
     
        
    }
    
    
    [self.collectionView reloadData];
}

- (void)btn2Move:(UIPanGestureRecognizer *)pan {
    
    CGPoint  point = [pan translationInView:self.circleCenterView];
    CGFloat width = self.circleCenterView.frame.size.width - self.moveColorView.frame.size.width / 2;
    
    CGRect originalFrame = self.moveColorView.frame;
    
    originalFrame.origin.x += point.x;
    originalFrame.origin.y += point.y;
    
    // 圆心
    CGPoint center = CGPointMake(CGRectGetMidX(originalFrame) - width / 2,CGRectGetMidY(originalFrame) - width /2);
    
    CGFloat offetX  = self.moveColorView.frame.size.width / 2;
    CGFloat offerY = self.moveColorView.frame.size.height / 2;
    if (center.x > 0) {
        
        offetX = offetX / 2;
    }
    if(center.y > 0) {
        
        offerY = offerY / 2;
    }
    
    CGFloat x2 = fabs(center.x - offetX ) * fabs(center.x - offetX);
    CGFloat y2 = fabs(center.y - offerY)  * fabs(center.y  - offerY) ;
    CGFloat length = sqrt(x2 + y2);
    if (length >= width / 2) {
        
        originalFrame = self.moveColorView.frame;
    }
    
    self.moveColorView.frame = originalFrame;
    [pan setTranslation:CGPointZero inView:self.circleCenterView];
    
    switch (pan.state) {
        case UIGestureRecognizerStateChanged:
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            // 输出当前ImageView上的颜色值
            UIColor*color = [self colorOfPoint:self.moveColorView.center];
            
            if (self.currentSelectModel) {
                
                self.currentSelectModel.color = color;
                [self.collectionView reloadData];
                NSInteger index = [self.cellModels indexOfObject:self.currentSelectModel];
                ZZColorRGBA *rgba = self.changeModel.colors[index];
                NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
                rgba.R = [rgbaArr[0] floatValue];
                rgba.G = [rgbaArr[1] floatValue];
                rgba.B = [rgbaArr[2] floatValue];
                
                self.lightImage.image = [UIImage imageNamed:self.changeModel.imageStr];
                self.lightView.image = [self.lightView.image imageWithColors:[ZZColorRGBA colorsFromRGBA:self.changeModel.colors]];
                // 改变index颜色
                
#pragma 这里就可以输出颜色了
                
            }
#pragma mark - 颜色输出
            NSLog(@"%@",color);
        }
            break;
            
        default:
            break;
    }
}

- (UIColor *)colorOfPoint:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    
    CGContextTranslateCTM(context, -point.x, -point.y);
    
    [self.circleCenterView.layer renderInContext:context];
    
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    
    return color;
}

#pragma mark - set & get
- (void)setModel:(ZZThemeCellModel *)model {

    _model = model;
    
    ZZThemeCellModel *changeModel = [ZZThemeCellModel new];
    changeModel.modelStyle = model.modelStyle;
    changeModel.title = model.title;
    changeModel.imageStr = model.imageStr;
    changeModel.colors = [NSMutableArray arrayWithArray:model.colors];
    self.changeModel = changeModel;
    
  
}

- (void)setChangeModel:(ZZThemeCellModel *)changeModel {
    
    _changeModel = changeModel;
    
    for (ZZColorRGBA *rgba in changeModel.colors) {
        
        ZZLightViewSettingCVCellModel *model =  [ZZLightViewSettingCVCellModel new];
        model.color = [rgba color];
        [self.cellModels addObject:model];
    }
    
    NSArray *arr = [ZZColorRGBA colorsFromRGBA:changeModel.colors];
    self.lightView.image = [self.lightView.image imageWithColors:arr];
}

- (NSMutableArray<ZZLightViewSettingCVCellModel *> *)cellModels {
    
    if (!_cellModels) {
        
        _cellModels = [NSMutableArray array];
    }
    return _cellModels;
}


@end
